package com.lc.ibps.platform.rest.component;

import java.util.HashMap;
import java.util.Map;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.lc.ibps.api.base.model.User;
import com.lc.ibps.base.core.constants.StringPool;
import com.lc.ibps.base.core.util.AppUtil;
import com.lc.ibps.base.core.util.string.StringUtil;
import com.lc.ibps.base.web.context.ContextUtil;
import com.lc.ibps.cloud.entity.APIResult;
import com.lc.ibps.components.upload.UploadStrategySelector;
import com.lc.ibps.components.upload.constants.FileParam;
import com.lc.ibps.components.upload.model.FileInfo;
import com.lc.ibps.components.upload.service.IFileInfoPersistenceService;
import com.lc.ibps.components.upload.service.IUploadService;
import com.lc.ibps.components.upload.util.FileInfoPersistenceFactory;
import com.lc.ibps.web.controller.BaseApiController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * 上传附件接口
 * TODO 断点续传暂时不做
 *
 * <pre>
 *  
 * 构建组：ibps-platform-webapi
 * 作者：zhongjh
 * 邮箱：zjh20140614@163.com
 * 日期：2018年8月1日-上午10:23:03
 * 版权：广州流辰信息技术有限公司版权所有
 * </pre>
 */
@RequestMapping(value = "/api/webapi/uploadService")
@Api(value = "/uploadService", tags = "系统管理-文件上传服务")
@RestController
public class UploadController extends BaseApiController {

	private UploadStrategySelector uploadStrategySelector;

	private IUploadService uploadService;

	public UploadController() {
		uploadStrategySelector = AppUtil.getBean(UploadStrategySelector.class);
	}

	public IUploadService getUploadService() throws Exception {
		return getUploadService(FileInfoPersistenceFactory.getIUploadResultPersistence());
	}

	public IUploadService getUploadService(String beanId) throws Exception {
		if (uploadService == null) {
			uploadService = uploadStrategySelector.getIUploadService();
			uploadService.setFileInfoPersistenceService(FileInfoPersistenceFactory.getIUploadResultPersistence(beanId));
		}
		return uploadService;
	}

	public IUploadService getUploadService(IFileInfoPersistenceService fileInfoPersistenceService) throws Exception {
		if (uploadService == null) {
			uploadService = uploadStrategySelector.getIUploadService();
			uploadService.setFileInfoPersistenceService(fileInfoPersistenceService);
		}
		return uploadService;
	}

	/**
	 * 上传文件入口
	 * 
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@ApiOperation(value = "文件上传", notes = "文件上传")
	@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
	public APIResult<FileInfo> uploadFile(
			@ApiParam(name = "file", value = "文件", required = true) 
			@RequestParam(name = "file", required = true)MultipartFile file
			) throws Exception {
		APIResult<FileInfo> result = new APIResult<>();
		Map<String, Object> params = new  HashMap<String, Object> ();
		this.getUploadService();
		FileInfo fileInfo = null;
		try {
			User user = ContextUtil.getCurrentUser();

			params.put(FileParam.CUR_USER_ID, user.getUserId());
			params.put(FileParam.CUR_USER_ACCOUNT, user.getAccount());
			params.put(FileParam.CUR_USER_NAME, user.getFullname());
			params.put(FileParam.ORIGINAL_FILE_NAME, file.getOriginalFilename());
			params.put(FileParam.FILE_SIZE, file.getSize());
			fileInfo = uploadService.uploadFile(file.getInputStream(), params);

			// 删除大文件，回填
			if (fileInfo != null)
				fileInfo.setFileBytes(null);
			result.setData(fileInfo);
		} catch (Exception e) {
			result = getExceptionResult(result, ERROR, "上传文件失败", e);
		}
	

		return result;
	}
//
//	/**
//	 * 检查文件是否存在，实现秒传
//	 *
//	 * @param fileMd5
//	 * @throws Exception
//	 */
//	@Path("/checkMd5")
//	@ApiOperation(value = "校验文件", notes = "检查文件是否存在，实现秒传")
//	@GET
//	public WebAPIResult checkMd5(@QueryParam("fileMd5") @ApiParam(value = "文件 MD5", required = true) String fileMd5) {
//		WebAPIResult result = new WebAPIResult();
//		try {
//			this.getUploadService();
//			boolean isExists = uploadService.checkMd5(fileMd5);
//			if (isExists) {
//				result.setResult(WebAPIResult.SUCCESS);
//			} else {
//				result.setResult(WebAPIResult.FAIL);
//			}
//		} catch (Exception e) {
//			result.setResult(WebAPIResult.ERROR);
//			result.setCause(e.getMessage());
//		}
//		return result;
//	}
//
//	/**
//	 * 
//	 * 检查分块文件
//	 *
//	 * @param uploadType
//	 * @param fileMd5
//	 * @param paramJson
//	 * @param isChunk
//	 * @param chunk
//	 * @param chunkSize
//	 * @param userId
//	 * @return
//	 * @throws Exception
//	 */
//	@Path("/checkChunk")
//	@ApiOperation(value = "校验文件", notes = "检查分块文件")
//	@POST
//	public WebAPIResult checkChunk(
//			@RequestParam("uploadType") @ApiParam(value = "控件的类型", required = true, defaultValue = "file") String uploadType,
//			@RequestParam("fileMd5") @ApiParam(value = "文件 MD5", required = true) String fileMd5,
//			@RequestParam("paramJson") @ApiParam(value = "自定义参数", required = false) String paramJson,
//			@RequestParam("isChunk") @ApiParam(value = "是否分片存储", required = true, defaultValue = "true") Boolean isChunk,
//			@RequestParam("chunk") @ApiParam(value = "当前分块下标", required = false) String chunk,
//			@RequestParam("chunkSize") @ApiParam(value = "当前分块大小", required = false) String chunkSize,
//			@RequestParam("userId") @ApiParam(value = "用户Id", required = true) String userId) throws Exception {
//		WebAPIResult result = new WebAPIResult();
//		try {
//			this.getUploadService();
//			Map<String, Object> map = getUploadParams(uploadType, paramJson, fileMd5, isChunk, chunk, chunkSize,
//					userId);
//			boolean isExists = uploadService.checkChunk(map);
//			if (isExists) {
//				result.setResult(WebAPIResult.SUCCESS);
//			} else {
//				result.setResult(WebAPIResult.FAIL);
//			}
//		} catch (Exception e) {
//			result.setResult(WebAPIResult.ERROR);
//		}
//		return result;
//	}
//
//	/**
//	 * 合并分块
//	 *
//	 * @param request
//	 * @param response
//	 * @throws Exception
//	 */
//	@Path("/mergeChunks")
//	@ApiOperation(value = "校验文件", notes = "检查分块文件")
//	@POST
//	public WebAPIResult mergeChunks(
//			@RequestParam("uploadType") @ApiParam(value = "控件的类型", required = true, defaultValue = "file") String uploadType,
//			@RequestParam("fileMd5") @ApiParam(value = "文件 MD5", required = true) String fileMd5,
//			@RequestParam("paramJson") @ApiParam(value = "自定义参数", required = false) String paramJson,
//			@RequestParam("isChunk") @ApiParam(value = "是否分片存储", required = true, defaultValue = "true") Boolean isChunk,
//			@RequestParam("chunk") @ApiParam(value = "当前分块下标", required = false) String chunk,
//			@RequestParam("chunkSize") @ApiParam(value = "当前分块大小", required = false) String chunkSize,
//			@RequestParam("filename") @ApiParam(value = "当前分块大小", required = false) String filename,
//			@RequestParam("fileSize") @ApiParam(value = "当前分块大小", required = false) String fileSize,
//			@RequestParam("fileExists") @ApiParam(value = "当前分块大小", required = false, defaultValue = "false") Boolean fileExists,
//			@RequestParam("userId") @ApiParam(value = "用户Id", required = true) String userId) {
//		WebAPIResult result = new WebAPIResult();
//		// 文件唯一标记 MD5
//		Map<String, Object> params = getUploadParams(uploadType, paramJson, fileMd5, isChunk, chunk, chunkSize, userId);
//		params.put(FileParam.ORIGINAL_FILE_NAME, filename);
//		params.put(FileParam.FILE_SIZE, fileSize);
//
//		FileInfo fileInfo = null;
//		try {
//			this.getUploadService();
//			if (fileExists) {
//				fileInfo = uploadService.saveFile(params);
//			} else {
//				fileInfo = uploadService.mergeChunks(params);
//			}
//			result.setResult(WebAPIResult.SUCCESS);
//		} catch (Exception e) {
//			result.setResult(WebAPIResult.ERROR);
//			result.setMessage(e.getMessage());
//		}
//		// 删除大文件，回填
//		if (fileInfo != null)
//			fileInfo.setFileBytes(null);
//		result.setData(fileInfo);
//		return result;
//	}

	/**
	 * 
	 * 删除文件
	 *
	 * @param deleteIds
	 * @return
	 */
	@ApiOperation(value = "删除文件", notes = "删除文件")
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public APIResult<String> delete(
			@ApiParam(name = "deleteIds",value = "文件标识IDs", required = true) 
			@RequestParam(name = "deleteIds", required = true)String deleteIds) {
		APIResult<String> result = new APIResult<>();
		if (StringUtil.isEmpty(deleteIds)) {
			result = getResult(result, FAIL, "删除失败,参数不能为空！");
			return result;
		}
		try {
			String[] ids = deleteIds.split(StringPool.COMMA);
			// 初始化上传Service
			this.getUploadService();
			uploadService.deleteFile(ids);
			result.setMessage("删除成功！");
		} catch (Exception e) {
			result = getExceptionResult(result, ERROR, "删除失败！", e);
		}
		return result;
	}

//	/**
//	 * 
//	 * 获取页面上传的参数
//	 *
//	 * @param request
//	 * @return
//	 */
//	private Map<String, Object> getUploadParams(HttpServletRequest request) {
//		String uploadType = RequestUtil.getString(request, "uploadType", "file"); // 控件的类型
//		String paramJson = RequestUtil.getString(request, "paramJson"); // 自定义参数
//		String fileMd5 = RequestUtil.getString(request, "fileMd5");// 文件唯一标记 MD5
//		Boolean isChunk = RequestUtil.getBoolean(request, "isChunk", true);// 是否分片存储
//		// 当前分块下标
//		String chunk = RequestUtil.getString(request, "chunk");
//		// 当前分块大小
//		String chunkSize = RequestUtil.getString(request, "chunkSize");
//		User user = ContextUtil.getCurrentUser();
//
//		Map<String, Object> params = new HashMap<String, Object>();
//
//		params.put(FileParam.UPLOAD_TYPE, uploadType);
//		params.put(FileParam.FILE_MD5, fileMd5);
//		params.put(FileParam.IS_CHUNK, isChunk);
//		params.put(FileParam.CHUNK, chunk);
//		params.put(FileParam.CHUNK_SIZE, chunkSize);
//
//		params.put(FileParam.CUR_USER_ID, user.getUserId());
//		params.put(FileParam.CUR_USER_ACCOUNT, user.getAccount());
//		params.put(FileParam.CUR_USER_NAME, user.getFullname());
//
//		if (StringUtil.isNotEmpty(paramJson)) {
//			try {
//				Map<String, Object> m = JsonUtil.getMapFromJson(paramJson);
//				if (BeanUtils.isNotEmpty(m))
//					params.putAll(m);
//			} catch (Exception e) {
//			}
//		}
//		return params;
//	}

	


}
